/**@author: Administrator
 * @date: 2013-3-6
 * @Description:
 */
package org.benxiong.iplay.ui.component;

import org.benxiong.iplay.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ToggleButton;

/**
 * @author Administrator
 *
 */
public class WeightPreference extends DialogPreference implements OnCheckedChangeListener{

	private EditText kgInput;
	private EditText poundsInput;
	private ToggleButton tb;
	
	SharedPreferences sp;
	public WeightPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		sp = context.getSharedPreferences("org.benxiong.iplay_preferences", Context.MODE_PRIVATE);
	}

	@Override
	protected void onBindDialogView(View view) {
		// TODO Auto-generated method stub
		super.onBindDialogView(view);
		tb = (ToggleButton) view.findViewById(R.id.toggle);
		tb.setOnCheckedChangeListener(this);
		kgInput = (EditText) view.findViewById(R.id.kg_input);
		poundsInput = (EditText) view.findViewById(R.id.pounds_input);
		
		//bind data and view
		if(sp.getString("measure", "1").equals("0")) {
			tb.setChecked(true);
			kgInput.setText(sp.getString("weight", "0"));
		} else {
			poundsInput.setText(sp.getString("weightPounds", "0"));
		}
	}

	@Override
	protected void onDialogClosed(boolean positiveResult) {
		// TODO Auto-generated method stub
		super.onDialogClosed(positiveResult);
		if (positiveResult) {
			Editor editor = sp.edit();
			String value = "";
			if (tb.isChecked()) {
				value = kgInput.getText().toString();
				setSummary(value+"KG");
				editor.putString("weight", value);
			} else {
				value = poundsInput.getText().toString();
				setSummary(value+"Pounds");
				editor.putString("weightPounds", value);
			}
			editor.putString("measure", tb.isChecked()?"0":"1");
			editor.commit();
			
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			//change to CM
			kgInput.setVisibility(View.VISIBLE);
			poundsInput.setVisibility(View.GONE);
		} else {
			//change to Inch
			kgInput.setVisibility(View.GONE);
			poundsInput.setVisibility(View.VISIBLE);
		}
	}

}
